<template>
  <view class="config-manager-container">
    <!-- 标题栏 -->
    <view class="header">
      <text class="title">配置管理</text>
      <text class="subtitle">管理系统配置和业务配置</text>
    </view>

    <!-- 操作按钮 -->
    <view class="action-bar">
      <button class="action-btn primary" @click="refreshConfigs">
        <text class="btn-text">刷新配置</text>
      </button>
      <button class="action-btn secondary" @click="showCreateModal">
        <text class="btn-text">新建配置</text>
      </button>
      <button class="action-btn info" @click="refreshCache">
        <text class="btn-text">刷新缓存</text>
      </button>
    </view>

    <!-- 配置分组列表 -->
    <view class="section">
      <view class="section-title">
        <text class="title-text">配置分组</text>
        <text class="count">({{ configGroups.length }})</text>
      </view>
      
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-else-if="configGroups.length === 0" class="empty">
        <text>暂无配置分组</text>
      </view>
      
      <view v-else class="group-list">
        <view 
          v-for="(group, index) in configGroups" 
          :key="index" 
          class="group-item"
          @click="selectGroup(group)"
        >
          <view class="group-header">
            <text class="group-name">{{ group.group_name }}</text>
            <text class="group-count">{{ group.configs.length }}个配置</text>
          </view>
          <view class="group-desc">
            <text>{{ group.description || '暂无描述' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 配置详情 -->
    <view v-if="selectedGroup" class="section">
      <view class="section-title">
        <text class="title-text">{{ selectedGroup.group_name }} 配置</text>
        <button class="close-btn" @click="closeGroup">关闭</button>
      </view>
      
      <view class="config-list">
        <view 
          v-for="(config, index) in selectedGroup.configs" 
          :key="index" 
          class="config-item"
        >
          <view class="config-header">
            <text class="config-key">{{ config.config_key }}</text>
            <view class="config-actions">
              <button class="edit-btn" @click="editConfig(config)">编辑</button>
            </view>
          </view>
          <view class="config-content">
            <text class="config-value">{{ formatConfigValue(config.config_value) }}</text>
          </view>
          <view class="config-meta">
            <text class="config-type">{{ config.config_type }}</text>
            <text class="config-desc">{{ config.config_desc || '暂无描述' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 微信配置 -->
    <view class="section">
      <view class="section-title">
        <text class="title-text">微信配置</text>
      </view>
      
      <view class="wechat-config">
        <view class="config-row">
          <text class="label">AppID:</text>
          <text class="value">{{ wechatConfig.app_id || '未设置' }}</text>
        </view>
        <view class="config-row">
          <text class="label">API Base:</text>
          <text class="value">{{ wechatConfig.api_base || '未设置' }}</text>
        </view>
        <button class="action-btn secondary" @click="showWechatConfigModal">
          <text class="btn-text">设置微信配置</text>
        </button>
      </view>
    </view>

    <!-- 业务配置 -->
    <view class="section">
      <view class="section-title">
        <text class="title-text">业务配置</text>
      </view>
      
      <view class="business-config">
        <view 
          v-for="(value, key) in businessConfig" 
          :key="key" 
          class="config-row"
        >
          <text class="label">{{ key }}:</text>
          <text class="value">{{ value }}</text>
        </view>
      </view>
    </view>

    <!-- 创建配置弹窗 -->
    <uni-popup ref="createPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">新建配置</text>
          <button class="close-btn" @click="closeCreateModal">×</button>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="label">配置键名:</text>
            <input 
              v-model="newConfig.config_key" 
              class="input" 
              placeholder="请输入配置键名"
            />
          </view>
          
          <view class="form-item">
            <text class="label">配置值:</text>
            <textarea 
              v-model="newConfig.config_value" 
              class="textarea" 
              placeholder="请输入配置值"
            />
          </view>
          
          <view class="form-item">
            <text class="label">配置类型:</text>
            <picker 
              :value="typeIndex" 
              :range="configTypes" 
              @change="onTypeChange"
            >
              <view class="picker">{{ configTypes[typeIndex] }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="label">配置分组:</text>
            <input 
              v-model="newConfig.config_group" 
              class="input" 
              placeholder="请输入配置分组"
            />
          </view>
          
          <view class="form-item">
            <text class="label">配置描述:</text>
            <textarea 
              v-model="newConfig.config_desc" 
              class="textarea" 
              placeholder="请输入配置描述"
            />
          </view>
          
          <view class="form-item">
            <text class="label">是否加密:</text>
            <switch 
              :checked="newConfig.is_encrypted" 
              @change="onEncryptedChange"
            />
          </view>
          
          <view class="form-item">
            <text class="label">是否系统配置:</text>
            <switch 
              :checked="newConfig.is_system" 
              @change="onSystemChange"
            />
          </view>
        </view>
        
        <view class="popup-footer">
          <button class="btn cancel" @click="closeCreateModal">取消</button>
          <button class="btn primary" @click="createConfig">创建</button>
        </view>
      </view>
    </uni-popup>

    <!-- 编辑配置弹窗 -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">编辑配置</text>
          <button class="close-btn" @click="closeEditModal">×</button>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="label">配置键名:</text>
            <text class="value">{{ editingConfig.config_key }}</text>
          </view>
          
          <view class="form-item">
            <text class="label">配置值:</text>
            <textarea 
              v-model="editingConfig.config_value" 
              class="textarea" 
              placeholder="请输入配置值"
            />
          </view>
        </view>
        
        <view class="popup-footer">
          <button class="btn cancel" @click="closeEditModal">取消</button>
          <button class="btn primary" @click="updateConfig">保存</button>
        </view>
      </view>
    </uni-popup>

    <!-- 微信配置弹窗 -->
    <uni-popup ref="wechatPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">设置微信配置</text>
          <button class="close-btn" @click="closeWechatModal">×</button>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="label">AppID:</text>
            <input 
              v-model="wechatForm.app_id" 
              class="input" 
              placeholder="请输入微信AppID"
            />
          </view>
          
          <view class="form-item">
            <text class="label">AppSecret:</text>
            <input 
              v-model="wechatForm.app_secret" 
              class="input" 
              type="password"
              placeholder="请输入微信AppSecret"
            />
          </view>
        </view>
        
        <view class="popup-footer">
          <button class="btn cancel" @click="closeWechatModal">取消</button>
          <button class="btn primary" @click="setWechatConfig">保存</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import configManager from '@/utils/config'

export default {
  data() {
    return {
      loading: false,
      configGroups: [],
      selectedGroup: null,
      wechatConfig: {},
      businessConfig: {},
      
      // 新建配置表单
      newConfig: {
        config_key: '',
        config_value: '',
        config_type: 'string',
        config_group: '',
        config_desc: '',
        is_encrypted: false,
        is_system: false
      },
      
      // 编辑配置表单
      editingConfig: {
        config_key: '',
        config_value: ''
      },
      
      // 微信配置表单
      wechatForm: {
        app_id: '',
        app_secret: ''
      },
      
      // 配置类型选项
      configTypes: ['string', 'number', 'boolean', 'json', 'array'],
      typeIndex: 0
    }
  },
  
  onLoad() {
    this.loadData()
  },
  
  methods: {
    /**
     * 加载数据
     */
    async loadData() {
      this.loading = true
      
      try {
        // 初始化配置管理器
        await configManager.initialize()
        
        // 加载配置分组
        await this.loadConfigGroups()
        
        // 加载公开配置
        this.wechatConfig = configManager.getWechatConfig()
        this.businessConfig = configManager.getBusinessConfig()
        
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 加载配置分组
     */
    async loadConfigGroups() {
      try {
        const groups = await configManager.getConfigGroups()
        this.configGroups = groups || []
      } catch (error) {
        console.error('加载配置分组失败:', error)
        this.configGroups = []
      }
    },
    
    /**
     * 选择配置分组
     */
    async selectGroup(group) {
      try {
        const groupData = await configManager.getConfigByGroup(group.group_name)
        this.selectedGroup = groupData
      } catch (error) {
        console.error('加载分组配置失败:', error)
        uni.showToast({
          title: '加载分组配置失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 关闭分组
     */
    closeGroup() {
      this.selectedGroup = null
    },
    
    /**
     * 刷新配置
     */
    async refreshConfigs() {
      try {
        await this.loadConfigGroups()
        uni.showToast({
          title: '配置刷新成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('刷新配置失败:', error)
        uni.showToast({
          title: '刷新配置失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 刷新缓存
     */
    async refreshCache() {
      try {
        await configManager.refreshCache()
        await this.loadData()
        uni.showToast({
          title: '缓存刷新成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('刷新缓存失败:', error)
        uni.showToast({
          title: '刷新缓存失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 显示创建配置弹窗
     */
    showCreateModal() {
      this.resetNewConfig()
      this.$refs.createPopup.open()
    },
    
    /**
     * 关闭创建配置弹窗
     */
    closeCreateModal() {
      this.$refs.createPopup.close()
    },
    
    /**
     * 重置新建配置表单
     */
    resetNewConfig() {
      this.newConfig = {
        config_key: '',
        config_value: '',
        config_type: 'string',
        config_group: '',
        config_desc: '',
        is_encrypted: false,
        is_system: false
      }
      this.typeIndex = 0
    },
    
    /**
     * 配置类型改变
     */
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.newConfig.config_type = this.configTypes[this.typeIndex]
    },
    
    /**
     * 加密开关改变
     */
    onEncryptedChange(e) {
      this.newConfig.is_encrypted = e.detail.value
    },
    
    /**
     * 系统配置开关改变
     */
    onSystemChange(e) {
      this.newConfig.is_system = e.detail.value
    },
    
    /**
     * 创建配置
     */
    async createConfig() {
      if (!this.newConfig.config_key || !this.newConfig.config_value || !this.newConfig.config_group) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
      
      try {
        await configManager.createConfig(this.newConfig)
        this.closeCreateModal()
        await this.loadConfigGroups()
        uni.showToast({
          title: '配置创建成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('创建配置失败:', error)
        uni.showToast({
          title: '创建配置失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 编辑配置
     */
    editConfig(config) {
      this.editingConfig = {
        config_key: config.config_key,
        config_value: config.config_value
      }
      this.$refs.editPopup.open()
    },
    
    /**
     * 关闭编辑弹窗
     */
    closeEditModal() {
      this.$refs.editPopup.close()
    },
    
    /**
     * 更新配置
     */
    async updateConfig() {
      try {
        await configManager.updateConfig(
          this.editingConfig.config_key,
          this.editingConfig.config_value
        )
        this.closeEditModal()
        
        // 如果当前有选中的分组，重新加载
        if (this.selectedGroup) {
          await this.selectGroup(this.selectedGroup)
        }
        
        uni.showToast({
          title: '配置更新成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('更新配置失败:', error)
        uni.showToast({
          title: '更新配置失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 显示微信配置弹窗
     */
    showWechatConfigModal() {
      this.wechatForm = {
        app_id: this.wechatConfig.app_id || '',
        app_secret: ''
      }
      this.$refs.wechatPopup.open()
    },
    
    /**
     * 关闭微信配置弹窗
     */
    closeWechatModal() {
      this.$refs.wechatPopup.close()
    },
    
    /**
     * 设置微信配置
     */
    async setWechatConfig() {
      if (!this.wechatForm.app_id || !this.wechatForm.app_secret) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
      
      try {
        await configManager.setWechatConfig(
          this.wechatForm.app_id,
          this.wechatForm.app_secret
        )
        this.closeWechatModal()
        this.wechatConfig = configManager.getWechatConfig()
        uni.showToast({
          title: '微信配置设置成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('设置微信配置失败:', error)
        uni.showToast({
          title: '设置微信配置失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 格式化配置值显示
     */
    formatConfigValue(value) {
      if (typeof value === 'object') {
        return JSON.stringify(value)
      }
      return String(value)
    }
  }
}
</script>

<style scoped>
.config-manager-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
  display: block;
}

.action-bar {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.action-btn {
  flex: 1;
  border: none;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.action-btn.primary {
  background-color: #007aff;
  color: #fff;
}

.action-btn.secondary {
  background-color: #5856d6;
  color: #fff;
}

.action-btn.info {
  background-color: #34c759;
  color: #fff;
}

.btn-text {
  font-size: 28rpx;
}

.section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.count {
  font-size: 24rpx;
  color: #999;
}

.loading, .empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

.group-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.group-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border: 1rpx solid #e9ecef;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.group-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.group-count {
  font-size: 24rpx;
  color: #666;
  background-color: #e9ecef;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.group-desc {
  font-size: 26rpx;
  color: #666;
}

.config-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.config-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  border: 1rpx solid #e9ecef;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.config-key {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.edit-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
}

.config-content {
  margin-bottom: 10rpx;
}

.config-value {
  font-size: 26rpx;
  color: #666;
  word-break: break-all;
}

.config-meta {
  display: flex;
  gap: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.config-type {
  background-color: #e9ecef;
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
}

.close-btn {
  background: none;
  border: none;
  font-size: 32rpx;
  color: #999;
  padding: 0;
}

.wechat-config, .business-config {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.config-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.config-row:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.value {
  font-size: 28rpx;
  color: #666;
  max-width: 60%;
  text-align: right;
  word-break: break-all;
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 16rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 25rpx;
}

.form-item .label {
  display: block;
  margin-bottom: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.input, .textarea {
  width: 100%;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.picker {
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
}

.popup-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn {
  flex: 1;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.btn.cancel {
  background-color: #f8f9fa;
  color: #666;
}

.btn.primary {
  background-color: #007aff;
  color: #fff;
}
</style> 